package com.hsj.xiaokang.arrayrevert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数组的逆转
 * http://blog.csdn.net/u011699931/article/details/52554787
 * @Description:TODO
 * @author:hsj qq:2356899074
 * @time:2017年11月8日 上午10:25:38
 */
public class ArrayRevert {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(ArrayRevert.class); 
	
	/**
	 * 入口
	 * @Description:TODO
	 * @author:hsj qq:2356899074
	 * @time:2017年11月8日 上午10:36:06
	 * @param args
	 */
	public static void main(String[] args) {
		try {
//			testReverseSelf();
			
//			testArrayList();
			
			testCollectionsReverse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 直接数组元素对换
	 * @Description:TODO
	 * @author:hsj qq:2356899074
	 * @time:2017年11月8日 上午10:35:25
	 * @throws Exception
	 */
	public static void testReverseSelf() throws Exception {
		
	    LOGGER.info("use ReverseSelf {}","start!");

	    String[] strings = { "ramer", "jelly", "bean", "cake" };
	    
	    LOGGER.info("\t {}", Arrays.toString(strings));
	    
	    for (int start = 0, end = strings.length - 1; start < end; start++, end--) {
	        String temp = strings[end];
	        strings[end] = strings[start];
	        strings[start] = temp;
	    }
	    
	    LOGGER.info("\t {}", Arrays.toString(strings));
	}
	
	/**
	 * 使用ArrayList: ArrayList存入和取出的顺序是一样的,可以利用这里特性暂时存储数组元素.
	 * @Description:TODO
	 * @author:hsj qq:2356899074
	 * @time:2017年11月8日 上午10:42:09
	 * @throws Exception
	 */
	public static void testArrayList() throws Exception {
	    LOGGER.info("use ArrayList method {}","start!");
	    
	    String[] strings = { "ramer", "jelly", "bean", "cake" };
	    
	    LOGGER.info("\t {}", Arrays.toString(strings));
	    
	    List<String> list = new ArrayList<>(strings.length);
	    for (int i = strings.length - 1; i >= 0; i--) {
	        list.add(strings[i]);
	    }
	    strings = list.toArray(strings);
	    
	    LOGGER.info("\t {}", Arrays.toString(strings));
	}
	
	/**
	 * 使用Collections和Arrays工具类
	 * @Description:TODO
	 * @author:hsj qq:2356899074
	 * @time:2017年11月8日 上午10:44:58
	 * @throws Exception
	 */
	public static void testCollectionsReverse() throws Exception {
	    LOGGER.info("use Collections.reverse() method {}","start!");

	    String[] strings = { "ramer", "jelly", "bean", "cake" };
	    LOGGER.info("\t {}", Arrays.toString(strings));
	    
	    // 这种方式仅针对引用类型,对于基本类型如:
	    // char[] cs = {'a','b','c','g','d'};
	    // 应该定义或转换成对应的引用类型: 
	    // Character[] cs = {'a','b','c','g','d'};
	    Collections.reverse(Arrays.asList(strings));
	    
	    LOGGER.info("\t {}", Arrays.toString(strings));
	}
}
